package blog.controller;

import blog.entity.QueryJson;
import blog.entity.ResultJson;
import blog.pojo.User;
import blog.service.RoleService;
import blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/find")
    public ResultJson find() throws Exception {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println(name);
        User user = userService.selectByName(name);
        user.setRole(roleService.selectById(user.getRoleId()));
        return ResultJson.isSuccess(user);
    }

    @RequestMapping("/updPassword")
    public ResultJson updPassword(@RequestBody QueryJson<User> queryJson) throws Exception {
        System.out.println(queryJson.getOthers().toString());
        Map<String, String> map = queryJson.getOthers();
        if (map == null) {
            return ResultJson.ARGUMENT_NULL;
        }
        String oldPassword = map.get("oldPassword");
        if (oldPassword == null) {
            return ResultJson.PASSWORD_OLD_NULL;
        }
        String newPassword1 = map.get("newPassword1");
        if (newPassword1 == null) {
            return ResultJson.PASSWORD_NEW_NULL;
        }
        String newPassword2 = map.get("newPassword2");
        if(newPassword2 == null) {
            return ResultJson.PASSWORD_NEW_NULL;
        }
        if(!newPassword1.equals(newPassword2)){
            return ResultJson.PASSWORD_NEW_SAME_ERROR;
        }
        if(newPassword1.length() < 6){
            return ResultJson.PASSWORD_SHORTER;
        }
        if(newPassword1.length() > 16){
            return ResultJson.PASSWORD_LONGER;
        }
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.selectByName(name);

        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if(!user.getPassword().equals(oldPassword)){
            return ResultJson.PASSWORD_OLD_ERROR;
        }
        newPassword1 = DigestUtils.md5DigestAsHex(newPassword1.getBytes());
        if(!userService.updatePassword(name, newPassword1)){
            return ResultJson.UPDATE_ERROR;
        }
        return ResultJson.SUCCESS;
    }

}
